package com.sywb.chuangyebao.widget;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.sywb.chuangyebao.R;

import org.bining.footstone.App;
import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.BaseRecyclerDivider;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemClickListener;
import org.bining.footstone.utils.ScreenUtils;

import java.util.ArrayList;


/**
 * 功能描述：标题按钮上的弹窗（继承自PopupWindow）
 */
public class MenuPopup extends PopupWindow {

    // 坐标的位置（x、y）
    private final int[] mLocation = new int[2];
    private Context mContext;
    // 实例化一个矩形
    private Rect mRect = new Rect();
    // 屏幕的宽度
    private int mScreenWidth;

    // 弹窗子类项选中时的监听
    private OnItemOnClickListener mItemOnClickListener;

    // 定义列表对象
    private RecyclerView mRecycler;

    // 定义弹窗子类项列表
    private ArrayList<String> mActionItems = new ArrayList<>();

    private MenuAdapter menuAdapter;

    private BaseRecyclerDivider recyclerDivider;
    private int left;
    private int top;
    private int right;
    private int bottom;
    private boolean isPadding;
    private boolean hasIcon;

    public MenuPopup(Context context) {
        this.mContext = context;
        // 设置弹窗的布局界面
        setContentView(LayoutInflater.from(context).inflate(R.layout.layout_menu_popup, null));
        setFocusable(true);// 设置可以获得焦点
        setTouchable(true); // 设置弹窗内可点击
        setOutsideTouchable(true); // 设置弹窗外可点击
//        setBackgroundDrawable(context.getResources().getDrawable(R.drawable.popup_menu));//设置无背景
//        setBackgroundDrawable(new BitmapDrawable());
        setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        setAnimationStyle(R.style.popup_anim);//设置弹出动画
        mScreenWidth = ScreenUtils.getScreenWidth();
        // 设置弹窗的宽度和高度
        setWidth((int) (mScreenWidth * 0.45));
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);


        mRecycler = getContentView().findViewById(R.id.common_recycler);
//        mRecycler.setBackgroundResource(android.R.color.transparent);
        mRecycler.setPadding(0, ScreenUtils.dp2px(1), 0, 0);
        recyclerDivider = new BaseRecyclerDivider();
        recyclerDivider.setDivider((int) mContext.getResources().getDimension(R.dimen.dp_05));
        recyclerDivider.setColor(ContextCompat.getColor(App.app(), R.color.colorLineDivider));
        mRecycler.addItemDecoration(recyclerDivider);

        menuAdapter = new MenuAdapter(mContext);
        menuAdapter.setDatas(mActionItems);
        mRecycler.setAdapter(menuAdapter);
        mRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        menuAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                if (mItemOnClickListener != null) {
                    checkIndex = i;
                    mItemOnClickListener.onItemClick(mActionItems.get(i), i);
                    menuAdapter.notifyDataSetChanged();
                }
                dismiss();// 点击子类项后，弹窗消失
            }
        });
    }


    /**
     * 计算出来的位置，y方向就在anchorView的上面和下面对齐显示，x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化，就可以适当自己额外加入偏移来修正
     *
     * @param anchorView  呼出window的view
     * @param contentView window的内容布局
     * @return window显示的左上角的xOff, yOff坐标
     */
    private int[] calculatePopWindowPos(View anchorView, View contentView) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        //获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = mContext.getResources().getDisplayMetrics().heightPixels;
        final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
//        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
//        if (isNeedShowUp) {
        windowPos[0] = screenWidth - windowWidth;
        windowPos[1] = anchorLoc[1] - windowHeight;
//        } else {
//            windowPos[0] = screenWidth - windowWidth;
//            windowPos[1] = anchorLoc[1] + anchorHeight;
//        }
        return windowPos;
    }

    @Override
    public void setContentView(View contentView) {
        if (contentView != null) {
            contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            super.setContentView(contentView);
            addKeyListener(contentView);
        }
    }

    @Override
    public void setBackgroundDrawable(Drawable background) {
        mBackgroundDrawable = background;
        setOutsideTouchable(isOutsideTouchable());
    }


    private Drawable mBackgroundDrawable;

    @Override
    public void setOutsideTouchable(boolean touchable) {
        super.setOutsideTouchable(touchable);
        if (touchable) {
            if (mBackgroundDrawable == null) {
                mBackgroundDrawable = new ColorDrawable(0x00000000);
            }
            super.setBackgroundDrawable(mBackgroundDrawable);
        } else {
            super.setBackgroundDrawable(null);
        }
    }

    private float mShowAlpha = 0.88f;

//    @Override
//    public void showAtLocation(View parent, int gravity, int x, int y) {
//        super.showAtLocation(parent, gravity, x, y);
//        showAnimator().start();
//    }
//
//    @Override
//    public void showAsDropDown(View anchor) {
//        super.showAsDropDown(anchor);
//        showAnimator().start();
//    }
//
//    @Override
//    public void showAsDropDown(View anchor, int xoff, int yoff) {
//        super.showAsDropDown(anchor, xoff, yoff);
//        showAnimator().start();
//    }
//    @Override
//    public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) {
//        super.showAsDropDown(anchor, xoff, yoff, gravity);
//        showAnimator().start();
//    }
//    @Override
//    public void dismiss() {
//        super.dismiss();
//        dismissAnimator().start();
//    }

    /**
     * 窗口显示，窗口背景透明度渐变动画
     */
    private ValueAnimator showAnimator() {
        ValueAnimator animator = ValueAnimator.ofFloat(1.0f, mShowAlpha);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                setWindowBackgroundAlpha(alpha);
            }
        });
        animator.setDuration(360);
        return animator;
    }

    /**
     * 窗口隐藏，窗口背景透明度渐变动画
     */
    private ValueAnimator dismissAnimator() {
        ValueAnimator animator = ValueAnimator.ofFloat(mShowAlpha, 1.0f);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                setWindowBackgroundAlpha(alpha);
            }
        });
        animator.setDuration(320);
        return animator;
    }

    /**
     * 为窗体添加outside点击事件
     */
    private void addKeyListener(View contentView) {
        if (contentView != null) {
            contentView.setFocusable(true);
            contentView.setFocusableInTouchMode(true);
            contentView.setOnKeyListener(new View.OnKeyListener() {

                @Override
                public boolean onKey(View view, int keyCode, KeyEvent event) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_BACK:
                            dismiss();
                            return true;
                        default:
                            break;
                    }
                    return false;
                }
            });
        }
    }

    /**
     * 控制窗口背景的不透明度
     */
    private void setWindowBackgroundAlpha(float alpha) {
        Window window = ((Activity) mContext).getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.alpha = alpha;
        window.setAttributes(layoutParams);
    }

    /**
     * 显示弹窗列表界面
     */
    public void show(View view) {
//        // 获得点击屏幕的位置坐标
//        view.getLocationOnScreen(mLocation);
//        // 设置矩形的大小
//        mRect.set(mLocation[0], mLocation[1], mLocation[0] + view.getWidth(), mLocation[1] + view.getHeight());
//        // 显示弹窗的位置,可微调
//        showAtLocation(view, Gravity.NO_GRAVITY, (int) (mScreenWidth - getWidth() - mContext.getResources().getDimension(R.dimen.dp_10)),
//                (int) (mRect.bottom - mContext.getResources().getDimension(R.dimen.dp_10)));


        int windowPos[] = calculatePopWindowPos(view, getContentView());
        int xOff = 20;// 可以自己调整偏移
        windowPos[0] -= xOff;
//        showAtLocation(view, Gravity.BOTTOM | Gravity.START, windowPos[0], windowPos[1]);
        showAsDropDown(view);
//        setBackgroundAlpha(0.5f);//设置屏幕透明度
    }

    /**
     * 添加子类项
     */
    public void addAction(int resId, String action) {
        if (!TextUtils.isEmpty(action)) {
            mActionItems.add(action);
            menuAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 添加子类项
     */
    public void addAction(String action) {
        if (!TextUtils.isEmpty(action)) {
            mActionItems.add(action);
            menuAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 清除子类项
     */
    public void cleanAction() {
        if (!mActionItems.isEmpty()) {
            mActionItems.clear();
            menuAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 根据位置删除子类项
     */
    public void removeAction(int position) {
        if (position < mActionItems.size()) {
            mActionItems.remove(position);
            menuAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 根据位置得到子类项
     */
    public String getAction(int position) {
        if (position < 0 || position > mActionItems.size()) {
            return null;
        }
        return mActionItems.get(position);
    }

    /**
     * 得到子类项数目
     */
    public int getActionCount() {
        if (mActionItems != null) {
            return mActionItems.size();
        } else return 0;
    }

    /**
     * 设置监听事件
     */
    public void setItemOnClickListener(OnItemOnClickListener onItemOnClickListener) {
        this.mItemOnClickListener = onItemOnClickListener;
    }

    /**
     * 设置图标的padding
     */
    public void setIconInVisible() {
        hasIcon = true;
    }

    /**
     * 设置图标的padding
     */
    public void setIconPadding(int left, int top, int right, int bottom) {
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
        this.isPadding = true;
    }

    /**
     * 弹窗子类项按钮监听事件
     */
    public interface OnItemOnClickListener {

        /**
         * Item点击回调方法
         */
        void onItemClick(String item, int position);
    }

    private int checkIndex;


    private class MenuAdapter extends BaseRecyclerAdapter<String> {

        MenuAdapter(Context context) {
            super(context, R.layout.item_popup_menu);
        }

        @Override
        protected void setItemData(ViewHolderHelper viewHolderHelper, int i, String model) {
            viewHolderHelper.setText(R.id.tv_name, model);
            viewHolderHelper.setVisibility(R.id.iv_check, i == checkIndex ? View.VISIBLE : View.GONE);
        }
    }
}